//
//  TDCell.m
//  ProjectDemo
//
//  Created by IOS3 on 2019/1/9.
//  Copyright © 2019 IOS3. All rights reserved.
//

#import "TDCell.h"
#import "SODownloader+TDManager.h"


static void * kStateContext = &kStateContext;
static void * kProgressContext = &kProgressContext;
static void * kSpeedContext = &kSpeedContext;


@interface TDCell ()
@property (weak, nonatomic) IBOutlet UILabel *speed;
@property (weak, nonatomic) IBOutlet UILabel *progress;
@property (weak, nonatomic) IBOutlet UILabel *info;
@property (weak, nonatomic) IBOutlet UIButton *button;

@end

@implementation TDCell



- (void)setModel:(TDModel *)model {
    if (_model) {
        [_model removeObserver:self forKeyPath:SODownloadItemStateObserveKeyPath];
        [_model removeObserver:self forKeyPath:SODownloadItemProgressObserveKeyPath];
        [_model removeObserver:self forKeyPath:SODownloadItemSpeedObserveKeyPath];
    }
    _model = model;
    if (_model) {
        [_model addObserver:self forKeyPath:SODownloadItemStateObserveKeyPath options:NSKeyValueObservingOptionNew context:kStateContext];
        [_model addObserver:self forKeyPath:SODownloadItemProgressObserveKeyPath options:NSKeyValueObservingOptionNew context:kProgressContext];
        [_model addObserver:self forKeyPath:SODownloadItemSpeedObserveKeyPath options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:kSpeedContext];
    }
//    if (model.so_downloadState == SODownloadStateNormal) {
//        [[SODownloader sharedInstance] downloadItem:_model];
//    }
    self.info.text = [model.savePath componentsSeparatedByString:@"/"].lastObject;
    [self updateState:model.so_downloadState];
}

- (IBAction)buttonClick:(UIButton *)sender {
    
    DLog(@"&&&&&&&    button click");
    
    switch (self.model.so_downloadState) {
        case SODownloadStateError:
        {
            [[SODownloader sharedInstance]resumeItem:self.model];
        }
            break;
        case SODownloadStatePaused:
        {
            [[SODownloader sharedInstance]resumeItem:self.model];
        }
            break;
        case SODownloadStateNormal:
        {
            [[SODownloader sharedInstance]downloadItem:self.model];
        }
            break;
        case SODownloadStateLoading:
        {
            [[SODownloader sharedInstance]pauseItem:self.model];
        }
            break;
        case SODownloadStateWait:
        {
            [[SODownloader sharedInstance]pauseItem:self.model];
        }
            break;
        default:
            break;
    }
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if (context == kStateContext) {
        SODownloadState newState = [change[NSKeyValueChangeNewKey]integerValue];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateState:newState];
        });
    } else if (context == kProgressContext) {
        double newProgress = [change[NSKeyValueChangeNewKey]doubleValue];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.progress.text = [NSString stringWithFormat:@"progress: %f", newProgress];
        });
    } else if (context == kSpeedContext) {
        NSNumber *value = change[NSKeyValueChangeNewKey];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ((NSNull *)value == [NSNull null]) {
                self.speed.text = @"0 Byte/s";
            } else {
                NSInteger speed = [value integerValue];
                if (speed < 1024) {
                    self.speed.text = [NSString stringWithFormat:@"%li Byte/s", speed];
                } else if (speed < 1024 * 1024) {
                    self.speed.text = [NSString stringWithFormat:@"%li kb/s", speed / 1024];
                } else {
                    self.speed.text = [NSString stringWithFormat:@"%li mb/s", speed / 1024 / 1024];
                }
            }
        });
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)updateState:(SODownloadState)state {
    switch (state) {
        case SODownloadStateWait:
            [self.button setTitle:@"等待中" forState:UIControlStateNormal];
            break;
        case SODownloadStatePaused:
            [self.button setTitle:@"已暂停" forState:UIControlStateNormal];
            break;
        case SODownloadStateError:
            [self.button setTitle:@"失败" forState:UIControlStateNormal];
            break;
        case SODownloadStateLoading:
            [self.button setTitle:@"下载中" forState:UIControlStateNormal];
            break;
        case SODownloadStateProcess:
            [self.button setTitle:@"处理中" forState:UIControlStateNormal];
            break;
        case SODownloadStateComplete:
            [self.button setTitle:@"已下载" forState:UIControlStateNormal];
            break;
        default:
            [self.button setTitle:@"未下载" forState:UIControlStateNormal];
            break;
    }
}

@end
